package at.fhooe.stefanirndorfer.sound;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.IntBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL10;
import org.lwjgl.util.WaveData;

import at.fhooe.stefanirndorfer.logging.Log;
//? right import?



public class OpenALWave {
	
	private String id;
	private IntBuffer buffer;
	private String path;
	
	public OpenALWave(String path, String id){
		this.path = path;
		this.id = id;
		buffer = BufferUtils.createIntBuffer(1);
		int errNo = -1;
		try {
			errNo = loadData();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.info(this, "Error No Buffer Generation");
			e.printStackTrace();
		}
		if(errNo != 1){
			Log.error(this, "Error loading Wave Data: " + id);
		}
	}

	
	private int loadData() throws FileNotFoundException {
		// Load wav data into a buffer.
		AL10.alGenBuffers(buffer);

		if(AL10.alGetError() != AL10.AL_NO_ERROR)
		  return AL10.AL_FALSE;

		WaveData waveFile = WaveData.create(new BufferedInputStream(new FileInputStream(path+id)));
		AL10.alBufferData(buffer.get(0), waveFile.format, waveFile.data, waveFile.samplerate);
		waveFile.dispose();
		return 1;
	}


	@Override
	public boolean equals(Object obj) {
		if (obj instanceof OpenALWave) {
			return id.equals(((OpenALWave) obj).getId());
		}
		return super.equals(obj);
	}
	

	public String getId() {
		return id;
	}
	
	public IntBuffer getBuffer(){
		return buffer;
	}
	
	public synchronized void deleteBuffer(){
		AL10.alDeleteBuffers(buffer);
		Log.info(this, "Buffer of " + id + " deleted!");
	}
	
	
}
